import 'dart:convert';

import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:xvideos/extension/date_string_extension.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/pay_kindly_tips_alert.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/pay_success_alert.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/vip_support_model.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';

import '../../../../../hj_utils/global.dart';
import '../../../assets_tool/app_colors.dart';
import '../../../assets_tool/images.dart';
import '../../../config/address.dart';
import '../../../hj_model/mine/excharge/dc_model.dart';
import '../../../hj_model/mine/excharge/recharge_type_list_model.dart';
import '../../../hj_model/mine/excharge/recharge_url_model.dart';
import '../../../hj_utils/api_service/mine_service.dart';
import '../../../routers/jump_router.dart';
import '../../../tools_base/global_store/store.dart';
import '../../../tools_base/loading/LoadingHelper.dart';
import '../../../tools_base/net/net_manager.dart';
import '../../web_page/h5_page.dart';
import '../mine_utils.dart';
import '../widgets/tap_widget.dart';

//在线支付弹窗
class OnlinePayPage extends StatefulWidget {
  final VipProductModel? vipProductModel; // vip 购买
  final RechargeTypeModel? coinRcModel; // 金币购买

  OnlinePayPage({
    Key? key,
    this.vipProductModel,
    this.coinRcModel,
  });

  @override
  _ChatGoodsBuyPageState createState() => _ChatGoodsBuyPageState();
}

class _ChatGoodsBuyPageState extends State<OnlinePayPage> {
  int payTypeIndex = 0;
  bool isPayLoading = false;
  bool showConpon = false;
  CouponModel? couponModel;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
      decoration: ShapeDecoration(
        color: Color(0xff202133),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.circular(12.r),
          ),
        ),
      ),
      child: () {
        /// 是否选择金币 此项目没有
        if (showConpon)
          return ChoseCouponView(
            backCallback: (model) {
              showConpon = false;
              couponModel = model;
              setState(() {});
            },
          );
        return Column(mainAxisSize: MainAxisSize.min, children: [
          Container(
            width: 36,
            height: 5,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(.2),
              borderRadius: BorderRadius.circular(100),
            ),
          ),
          18.sizeBoxH,
          Text(
            '选择支付方式',
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500, color: Colors.white),
          ),
          18.sizeBoxH,
          _buildPayList(), // 支付方式
          _buildTips(), // 支付提示
          _buildPayButton(), //支付按钮
          18.sizeBoxH,
          Center(
            child: EasyRichText(
              '支付中如有问题，请咨询 在线客服',
              defaultStyle: textStyle(12, Colors.white.withOpacity(.6), FontWeight.w500),
              patternList: [
                EasyRichTextPattern(
                  targetString: '在线客服',
                  style: textStyle(12, Color(0xffFFD460), FontWeight.w500),
                  recognizer: TapGestureRecognizer()..onTap = () => MineUtils.goCSPage(),
                ),
              ],
            ),
          ),
        ]);
      }(),
    );
  }

  //支付列表
  Widget _buildPayList() {
    List<RchgType> typeUI;
    if (widget.vipProductModel != null) {
      typeUI = widget.vipProductModel!.rchgTypeUI;
    } else {
      typeUI = widget.coinRcModel!.rechargeTypeListUI;
    }
    return Wrap(
      children: typeUI
          .map((e) => TapWidget(
                ontap: () {
                  if (e.type == 'coupon') {
                    showConpon = true;
                    setState(() {});
                  } else {
                    onChangedPayType(typeUI.indexOf(e));
                  }
                },
                Container(
                  height: 41,
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  margin: EdgeInsets.only(bottom: 20.h),
                  child: Row(
                    children: [
                      Image.asset(
                        e.getPayIcon(),
                        width: 36,
                      ),
                      13.sizeBoxW,
                      Expanded(
                        child: Text(
                          e.typeName.base64StringtoString(),
                          style: textStyle(16, Colors.white.withOpacity(.9), FontWeight.w500),
                        ),
                      ),
                      Image.asset(
                          payTypeIndex == typeUI.indexOf(e) ? 'mine_withdraw_sel.png'.mineImgPath : 'mine_withdraw_nor.png'.mineImgPath,
                          width: 16),
                    ],
                  ),
                ),
              ))
          .toList(),
    );
  }

  //支付方式
  onChangedPayType(int index) {
    setState(() {
      if (payTypeIndex == index) return;
      payTypeIndex = index;
    });
  }

  Widget _buildTips() {
    return Padding(
      padding: EdgeInsets.only(top: 0, bottom: 24.h, left: 16, right: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '支付小贴士：',
            style: textStyle(14, Colors.white.withOpacity(.9), FontWeight.w500),
          ),
          6.sizeBoxH,
          Text(
            '''1.因超时支付无法到账，请重新发起。
2.每天发起支付不能超过5次，连续发起且未支付，账号可能被加入黑名单。''',
            style: textStyle(12, Colors.white.withOpacity(.45), FontWeight.w400),
          ),
        ],
      ),
    );
  }

  Widget _buildPayButton() {
    RchgType rchgType;
    String price;
    if (widget.vipProductModel != null) {
      rchgType = widget.vipProductModel!.rchgTypeUI[payTypeIndex];
      if (widget.vipProductModel?.isPreSale ?? false) {
        // 预售的支付金额
        if (PreSaleProvider().canPayBalance())
          price = '¥${PreSaleProvider().preSaleModel?.detailModel?.balanceAmount ?? 0}支付尾款';
        else
          price = '¥${PreSaleProvider().preSaleModel?.detailModel?.advanceAmount ?? 0}立即预订';
      } else {
        if (widget.vipProductModel?.priceDiff != null)
          price = '${(widget.vipProductModel?.priceDiff ?? 0).abs()} 立即升级';
        else
          price = '¥${widget.vipProductModel?.discountedPriceUI ?? 0}/立即支付';
      }
    } else {
      rchgType = widget.coinRcModel!.rechargeTypeListUI[payTypeIndex];
      price = '¥${widget.coinRcModel?.moneyYuan ?? 0}/立即支付';
    }
    return GestureDetector(
      onTap: () {
        // 金币支付
        if (rchgType.type == "coin") {
          _goldCoinPayVip();
        } else if (rchgType.isOfficial == true) {
          // 正常购买
          if (widget.coinRcModel != null) {
            // 金币
            _dcPayFor(false, rchgType, widget.coinRcModel?.daichong, widget.coinRcModel?.id, widget.coinRcModel?.money);
          } else {
            // vip购买
            _dcPayFor(true, rchgType, widget.vipProductModel?.daichong, widget.vipProductModel?.productID,
                (widget.vipProductModel?.discountedPrice ?? 0) * 10);
          }
        } else {
          _onlinePayVip(rchgType);
        }
      },
      child: Container(
        alignment: Alignment.center,
        height: 44,
        decoration: ShapeDecoration(
          color: AppColors.actionRed,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(3),
          ),
        ),
        child: Text(
          price,
          style: TextStyle(fontWeight: FontWeight.w500, fontSize: 20.sp, color: Colors.white),
        ),
      ),
    );
  }

  Future _onlinePayVip(RchgType payType) async {
    String? rechargeType = payType.type;
    String? vipID;
    String? productId;
    bool isBuyVip = true; // true 购买VIP， false 购买金币
    if (widget.vipProductModel != null) {
      /// 购买会员卡
      vipID = widget.vipProductModel!.productID!;
      isBuyVip = true;
    } else {
      /// 购买钻石
      isBuyVip = false;
      productId = widget.coinRcModel!.id;
    }
    bool? pay = await Get.dialog(const PayKindlyTipsAlert());
    isPayLoading = false;
    if (pay == true) {
      if (isPayLoading) return;
      isPayLoading = true;
      LoadingHelper.showLoading();
      RechargeUrlModel? rechargeUrlModel = await MineService.chargeGoldCoin(
        rechargeType,
        productId: isBuyVip ? vipID : productId,
        isVip: isBuyVip,
        goldExtraID: couponModel != null ? couponModel?.cId : null,
        finalPayStatus: widget.vipProductModel?.isPreSale == true ? PreSaleProvider().preSaleModel?.detailModel?.balancePayment : null,
      );
      LoadingHelper.dismissLoading();
      if (rechargeUrlModel != null) {
        if (rechargeUrlModel.mode == "url") {
          await launchUrlToWeb(rechargeUrlModel.payUrl ?? '');
        } else if (rechargeUrlModel.mode == "sdk") {
          showToast("没有找到支付类型为:${payType.type} 的sdk");
          Get.back();
          return;
        }

        Get.back();
        Future.delayed(const Duration(milliseconds: 1500), () {
          //支付成功刷新vip到期时间
          Get.dialog(
            const Center(child: PaySuccessAlert()),
            barrierColor: const Color(0x22000000),
            barrierDismissible: true,
          );
        });
      }
      isPayLoading = false;
    }
  }

  Future _goldCoinPayVip() async {
    if (isPayLoading) return;
    isPayLoading = true;
    bool? pay = await Get.dialog(const PayKindlyTipsAlert());
    isPayLoading = false;
    if (pay == true) {
      LoadingHelper.showLoading();
      var result = await MineService.buyVipProduct(
        widget.vipProductModel?.productType,
        widget.vipProductModel?.productID,
        widget.vipProductModel?.productName,
        widget.vipProductModel?.discountedPrice,
        finalPayStatus: widget.vipProductModel?.isPreSale == true ? PreSaleProvider().preSaleModel?.detailModel?.balancePayment : null,
        diffPrice: widget.vipProductModel?.priceDiff,
      );
      LoadingHelper.dismissLoading();
      if (result != null) {
        if (result is Map && result['code'] != 200) {
          if (result['code'] == 8000) {
            // 余额不足
          }
        } else {
          showToast("购买成功");
          globalStore.refreshWallet();
          await globalStore.updateUserInfo();
          Get.back();
        }
      }
      isPayLoading = false;
    }
  }

  ///代充支付
  Future _dcPayFor(bool isVip, RchgType payType, DCModel? dcModel1, String? id, int? money) async {
    List<PayInfoModel> payList = dcModel1!.traders![0].payInfos!;
    PayInfoModel? payInfoModel;
    for (PayInfoModel model in payList) {
      if (model.payMethod == payType.payMethod) {
        payInfoModel = model;
        break;
      }
    }
    //设置默认值
    if (dcModel1.limit == 0) {
      dcModel1.limit = 500;
    }
    int payMoney = money ?? 0;
    if (payInfoModel!.payType!.contains(2) && payInfoModel.payType!.contains(3)) {
      if ((payMoney / 100) > dcModel1.limit!) {
        payInfoModel.payType = [3];
      } else {
        payInfoModel.payType = [2];
      }
    }

    if (payInfoModel.payType!.length >= 3) {
      if ((payMoney / 100) > dcModel1.limit!) {
        payInfoModel.payType = [1, 3];
      } else {
        payInfoModel.payType = [1, 2];
      }
    }

    var list = [payInfoModel];
    dcModel1.traders![0].payInfos = list;

    String? line = Address.baseHost;
    dcModel1.ordUrl = line! + dcModel1.ordUrl!;
    dcModel1.traderUrl = line + dcModel1.traderUrl!;
    dcModel1.chargeMoney = payMoney ~/ 100;
    String channel = payType.channel!;
    dcModel1.channel = channel;
    String token = await netManager.getToken();
    //bt64
    String models = json.encode(dcModel1).toString();
    String url = "$channel/?data=${_encodeBase64(models)}&token=$token";
    Get.to(
        H5Page(
          title: "代理充值",
          url: url,
        ),
        opaque: false);
  }

  String _encodeBase64(String data) {
    var content = utf8.encode(data);
    var digest = base64Encode(content);
    return digest;
  }
}

/// 优惠券
class ChoseCouponView extends StatefulWidget {
  final Function(CouponModel? selectModel) backCallback;
  const ChoseCouponView({super.key, required this.backCallback});

  @override
  State<ChoseCouponView> createState() => _ChoseCouponViewState();
}

class _ChoseCouponViewState extends State<ChoseCouponView> {
  bool _showLoading = true;
  final _dataSource = [];
  RefreshController? refreshController;
  int page = 1;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      fetchCoupons();
    });
  }

  fetchCoupons({bool isRefresh = true}) async {
    if (isRefresh) page = 1;
    final res = await MineService.fetchUserCouponByType(1, page: page);
    _showLoading = false;

    if (isRefresh) {
      refreshController?.refreshCompleted();
      _dataSource.clear();
    }
    if (_dataSource.length < 20) {
      refreshController?.loadNoData();
    } else {
      refreshController?.loadComplete();
    }
    _dataSource.addAll(res);
    page += 1;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: BoxConstraints(maxHeight: 400),
      child: Column(
        children: [
          // 18.sizeBoxH,
          Container(
            height: 41,
            alignment: Alignment.center,
            child: Container(
              width: 36,
              height: 5,
              decoration: BoxDecoration(color: Colors.black12, borderRadius: BorderRadius.circular(10)),
            ),
          ),
          Stack(
            // alignment: Alignment.center,
            children: [
              GestureDetector(
                onTap: () => widget.backCallback(null),
                child: Image.asset(
                  'common_back.png'.commonImgPath,
                  width: 18,
                  height: 18,
                  color: Colors.black.withOpacity(.9),
                ),
              ),
              Center(
                child: Text(
                  '选择加赠券',
                  style: TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.w600),
                ),
              )
            ],
          ),
          18.sizeBoxH,

          Expanded(
            child: pullYsRefresh(
                onRefresh: (refreshController) => fetchCoupons(),
                onLoading: (refreshController) => fetchCoupons(isRefresh: false),
                child: () {
                  if (_showLoading) return LoadingCenterWidget();
                  if (_dataSource.isEmpty) return CErrorWidget();
                  return ListView.separated(
                    separatorBuilder: (_, __) => 12.sizeBoxH,
                    itemCount: _dataSource.length,
                    itemBuilder: (BuildContext context, int index) {
                      return _buildCouponItem(_dataSource[index]);
                    },
                  );
                }(),
                onInit: (ctr) => refreshController = ctr),
          )
        ],
      ),
    );
  }

  Widget _buildCouponItem(CouponModel model) {
    return Container(
      height: 72,
      padding: EdgeInsets.only(left: 24, right: 11),
      alignment: Alignment.centerLeft,
      width: double.infinity,
      decoration: BoxDecoration(color: Color(0xffff891c).withOpacity(.4), borderRadius: BorderRadius.circular(4)),
      child: Row(
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                children: [
                  Image.asset(
                    'coupon_gold.png'.mineImgPath,
                    width: 16,
                    height: 16,
                  ),
                  4.sizeBoxH,
                  Text(
                    '${model.price ?? 0}',
                    style: TextStyle(color: Colors.black, fontSize: 24, fontWeight: FontWeight.w500, height: 33 / 24),
                  )
                ],
              ),
              Text(
                '充值加送金币',
                style: TextStyle(color: Colors.black.withOpacity(.6), fontSize: 12),
              )
            ],
          ),
          23.sizeBoxW,
          SizedBox(
            width: 1,
            height: 45,
            child: DecoratedBox(
              decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
                  // Colors.white.withOpacity(0),
                  Colors.black.withOpacity(0),
                  Colors.black.withOpacity(.5),
                  Colors.black.withOpacity(0)
                ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
              ),
            ),
          ),
          12.sizeBoxW,
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '金币加购券',
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 12,
                  ),
                ),
                4.sizeBoxH,
                Text(
                  '有效期：${model.expireTime?.utcTimeSToYMDHMString()}',
                  style: TextStyle(
                    color: Colors.black.withOpacity(.6),
                    fontSize: 8,
                  ),
                )
              ],
            ),
          ),
          11.sizeBoxW,
          GestureDetector(
            onTap: () => widget.backCallback(model),
            child: Container(
              decoration: BoxDecoration(color: Color(0xffF68216), borderRadius: BorderRadius.circular(22)),
              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 5),
              child: Text(
                '立即使用',
                style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w500),
              ),
            ),
          )
        ],
      ),
    );
  }
}
